/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.transport.sslHttpBase;

import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import cgl.narada.performance.PerformanceMeasurement;
import cgl.narada.transport.Link;
import cgl.narada.util.Log;

/**
 * Helper class to LinkFactoryImpl to manage a bundle of links.
 *
 * @author  John
 * @version 1.0
 */

public class LinkManager {

    private PerformanceMeasurement m_perfMeasurement;

    // Link ID => Link object.
    private Hashtable m_establishedLinks = new Hashtable();
    private Vector    m_shortLivedLinks  = new Vector();
    private LinkKiller m_linkKiller       = new LinkKiller();

    /**
     * ----------------------------------------------------------------
     */
    public LinkManager(PerformanceMeasurement measurement) {
        m_linkKiller.start();
        if (measurement == null) {
            m_perfMeasurement = new PerformanceMeasurement(this);
        } else {
            m_perfMeasurement = measurement;
        }
    }

    /**
     * ----------------------------------------------------------------
     */
    public void setMeasurementService(PerformanceMeasurement measurement) {
        if (measurement != null) {
            m_perfMeasurement = measurement;
        }
    }

    /**
     * ----------------------------------------------------------------
     */
    public void start() {
        m_perfMeasurement.start();
    }

    /**
     * ----------------------------------------------------------------
     */
    public void stop() {
        m_perfMeasurement.stop();
    }

    /**
     * ----------------------------------------------------------------
     */
    public PerformanceMeasurement getPerformanceMeasurement() {
        return m_perfMeasurement;
    }

    /**
     * ----------------------------------------------------------------
     */
    public synchronized void addLink(LinkImpl link) {
        if (m_establishedLinks.get(link.getLinkId()) == null) {
            m_establishedLinks.put(link.getLinkId(),link);
            m_perfMeasurement.addMeasurementListener(link);
            if (((LinkImpl)link).getKeepAliveEndTime() > 0) {
                m_shortLivedLinks.addElement(link);
            }
        }
    }

    /**
     * ----------------------------------------------------------------
     */
    public synchronized void renameLink(String oldID,String newID) {
        LinkImpl c = (LinkImpl)m_establishedLinks.remove(oldID);
        if (c != null) {
            Log.debug("LinkManager","Renamed link "+oldID+" to "+newID);
            c.m_linkID = newID;
            m_establishedLinks.put(newID,c);
        } else {
            Log.err("LinkManager","Unable to rename link "+oldID+" to "+newID);
        }
    }

    /**
     * ----------------------------------------------------------------
     */
    public synchronized void updateKeepAliveLink(Link link) {
        LinkImpl c = (LinkImpl)link;
        if (c.getKeepAliveEndTime() <= 0) {
            m_shortLivedLinks.removeElement(link);
        } else {
            if (!m_shortLivedLinks.contains(link)) {
                m_shortLivedLinks.addElement(link);
            }
        }
    }

    /**
     * ----------------------------------------------------------------
     */
    public synchronized void closeLink(LinkImpl link) {
        m_establishedLinks.remove(link.getLinkId());
        m_perfMeasurement.removeMeasurementListener(link);
    }

    /**
     * ----------------------------------------------------------------
     * Close all links associated with a transport.
     */
    public synchronized void closeAllLinks(Transport transport) {
        Enumeration e = m_establishedLinks.elements();
        while(e.hasMoreElements()) {
            Link c = (Link)e.nextElement();
            if (c instanceof LinkImpl) {
                LinkImpl ci = ((LinkImpl)c);
                if (ci.getTransport().equals(transport)) {
                    ci.closeLink();
                    if (m_shortLivedLinks.contains(ci)) {
                        m_shortLivedLinks.removeElement(ci);
                    }
                } else {
                }
            }
        }
    }

    /**
     * ----------------------------------------------------------------
     */
    public Link getLink(String id) {
        return (Link)m_establishedLinks.get(id);
    }

    /**
     * ----------------------------------------------------------------
     */
    public Enumeration getLinks() {
        return m_establishedLinks.elements();
    }

    /**
     * ----------------------------------------------------------------
     */
    public synchronized void closeAllLinks() {
        Enumeration e = m_establishedLinks.elements();
        while(e.hasMoreElements()) {
            Link c = (Link)e.nextElement();
            c.closeLink();
        }
        m_establishedLinks.clear();
        m_shortLivedLinks.removeAllElements();
    }

    /**
     * ----------------------------------------------------------------
     */
    public void dispose() {
        closeAllLinks();
        m_linkKiller.destroy();
    }


    /**
     * ==================================================================
     * Kills links whose keep alive have expired.
     */
    class LinkKiller extends Thread {

        private boolean m_stopped = false;

        /**
         * ----------------------------------------------------------------
         */
        public void run() {
            while(!m_stopped) {
                try { Thread.currentThread().sleep(5000); } catch (Exception ex) {}
                long currentTime = System.currentTimeMillis();
                Enumeration e = m_shortLivedLinks.elements();
                while(e.hasMoreElements()) {
                    LinkImpl c = (LinkImpl)e.nextElement();
                    if (currentTime > c.getKeepAliveEndTime()) {
                        Log.debug("LinkManager","Closing expired link "+
                                  c.getLinkId()+" suppose to die @ "+
                                  new Date(c.getKeepAliveEndTime()));
                        c.closeLink();
                        m_shortLivedLinks.removeElement(c);
                    }
                }
            }
        }

        /**
         * ----------------------------------------------------------------
         */
        public void destroy() {
            if (!m_stopped) {
                m_stopped = true;
                interrupt();
            }
        }
    }
}
